package com.xzqwjw.taskmanager.activity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.xzqwjw.taskmanager.R;
import com.leaderinfo.model.SortModel;
import com.xzqwjw.taskmanager.view.SideBarView;
import com.xzqwjw.taskmanager.view.SideBarView.OnTouchingLetterChangedListener;
import com.leaderinfo.utility.ClearEditText;
import com.leaderinfo.utility.PY_CharacterParser;
import com.leaderinfo.utility.PY_Comparator;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class ActivityAll extends Activity {

  private String strDBFile = "";

  private ListView sortListView;
  private SideBarView sideBar;
  private TextView dialog;
  private com.leaderinfo.utility.PYSortAdapter adapter;
  private ClearEditText mClearEditText;

  /**
   * 汉字转换成拼音的类
   */
  private PY_CharacterParser characterParser;
  private List<SortModel> SourceDateList;

  /**
   * 根据拼音来排列ListView里面的数据类
   */
  private PY_Comparator pinyinComparator;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_all);

    Intent objIT = getIntent();
    strDBFile = objIT.getStringExtra("DBFilePath");

    initViews();
  }

  private void initViews() {
    // 实例化汉字转拼音类
    characterParser = PY_CharacterParser.getInstance();

    pinyinComparator = new PY_Comparator();

    sideBar = (SideBarView) findViewById(R.id.sidebar);
    dialog = (TextView) findViewById(R.id.dialog);
    sideBar.setTextView(dialog);

    // 设置右侧触摸监听
    sideBar.setOnTouchingLetterChangedListener(new OnTouchingLetterChangedListener() {

      @Override
      public void onTouchingLetterChanged(String s) {
        // 该字母首次出现的位置
        int position = adapter.getPositionForSection(s.charAt(0));
        if (position != -1) {
          sortListView.setSelection(position);
        }

      }
    });

    sortListView = (ListView) findViewById(R.id.lv_name);
    sortListView.setOnItemClickListener(new OnItemClickListener() {
      @Override
      public void onItemClick(AdapterView<?> parent, View view,
                              int position, long id) {
        // 这里要利用adapter.getItem(position)来获取当前position所对应的对象
        String strAID = ((SortModel) adapter.getItem(position)).getID();
        Intent objIT = new Intent(ActivityAll.this,
            ActivityShowInfo.class);
        objIT.putExtra("AID", strAID);
        objIT.putExtra("DBFilePath", strDBFile);
        startActivity(objIT);
        // Toast.makeText(
        // getApplication(),
        // ((SortModel) adapter.getItem(position)).getName()
        // + ((SortModel) adapter.getItem(position))
        // .getID(), Toast.LENGTH_SHORT).show();
      }
    });

    // SourceDateList =
    // filledData(getResources().getStringArray(R.array.date));
    List<String[]> listData = null;
    try {
      com.leaderinfo.dao.PartyInfoDao objDaoPartyInfo = new com.leaderinfo.dao.PartyInfoDao(strDBFile);
      listData = objDaoPartyInfo.getAllIDName();
    } catch (Exception e) {
      e.printStackTrace();
    }
    SourceDateList = filledData(listData);

    // 根据a-z进行排序源数据
    Collections.sort(SourceDateList, pinyinComparator);
    adapter = new com.leaderinfo.utility.PYSortAdapter(this, SourceDateList);
    sortListView.setAdapter(adapter);

    mClearEditText = (ClearEditText) findViewById(R.id.filter_edit);

    // 根据输入框输入值的改变来过滤搜索
    mClearEditText.addTextChangedListener(new TextWatcher() {

      @Override
      public void onTextChanged(CharSequence s, int start, int before,
                                int count) {
        // 当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
        filterData(s.toString());
      }

      @Override
      public void beforeTextChanged(CharSequence s, int start, int count,
                                    int after) {
      }

      @Override
      public void afterTextChanged(Editable s) {
      }
    });
  }

  /**
   * 为ListView填充数据
   *
   * @param date
   * @return
   */
  private List<SortModel> filledData(List<String[]> listData) {
    List<SortModel> mSortList = new ArrayList<SortModel>();
    String[] arrIDName = {"", ""};
    if (listData != null) {
      for (int i = 0; i < listData.size(); i++) {
        SortModel sortModel = new SortModel();
        arrIDName = listData.get(i);
        sortModel.setName(arrIDName[1]);
        sortModel.setID(arrIDName[0]);
        // 汉字转换成拼音
        String pinyin = characterParser.getSelling(arrIDName[1]);
        String sortString = pinyin.substring(0, 1).toUpperCase();

        // 正则表达式，判断首字母是否是英文字母
        if (sortString.matches("[A-Z]")) {
          sortModel.setSortLetters(sortString.toUpperCase());
        } else {
          sortModel.setSortLetters("#");
        }

        mSortList.add(sortModel);
      }
      return mSortList;
    } else {
      return null;
    }

  }

  /**
   * 根据输入框中的值来过滤数据并更新ListView
   *
   * @param filterStr
   */
  private void filterData(String filterStr) {
    List<SortModel> filterDateList = new ArrayList<SortModel>();

    if (TextUtils.isEmpty(filterStr)) {
      filterDateList = SourceDateList;
    } else {
      filterDateList.clear();
      for (SortModel sortModel : SourceDateList) {
        String name = sortModel.getName();
        if (name.indexOf(filterStr.toString()) != -1
            || characterParser.getSelling(name).startsWith(
            filterStr.toString())) {
          filterDateList.add(sortModel);
        }
      }
    }

    // 根据a-z进行排序
    Collections.sort(filterDateList, pinyinComparator);
    adapter.updateListView(filterDateList);
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_all, menu);
    return true;
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.action_settings) {
      return true;
    }
    return super.onOptionsItemSelected(item);
  }

}
